package cn.com.infohold.smartcity.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.lang.reflect.Type;

import cn.com.infohold.smartcity.R;
import cn.com.infohold.smartcity.api.HttpEvent;
import cn.com.infohold.smartcity.api.SDK;
import cn.com.infohold.smartcity.api.bean.LandResult;
import cn.com.infohold.smartcity.api.bean.LogInResult;
import cn.com.infohold.smartcity.api.bean.UpdateInfo;
import cn.com.infohold.smartcity.api.bean.UserInfo;
import cn.com.infohold.smartcity.api.bean.Version;
import cn.com.infohold.smartcity.data.XmlConfig;
import cn.com.infohold.smartcity.data.XmlData;
import cn.com.infohold.smartcity.parent.ParentActivity;
import cn.com.infohold.smartcity.update.ApkVersion;
import cn.com.infohold.smartcity.update.UpdateXml;
import cn.com.infohold.smartcity.utils.GsonUtil;
import cn.com.infohold.smartcity.utils.RequestCode;
import cn.com.infohold.smartcity.weex.WeexLoader;
import cn.com.infohold.smartcity.weex.update.OnUpdateListening;
import cn.com.infohold.smartcity.weex.update.WeexUpdate;
import cn.com.infohold.smartcity.weex.update.WeexVersion;
import cn.pedant.SweetAlert.SweetAlertDialog;
import common.annotation.ViewInject;
import common.dialog.ProgressDialog;
import common.view.progress.Progressbar;
import library.http.Download;
import library.http.HttpCallback;
import library.http.progress.HttpDownloadListener;
import library.utils.ApkUtils;
import library.utils.DisplayUtil;
import library.utils.Logger;
import library.utils.Utils;

/**
 * Created by Mr.Fan on 2016-5-4.
 */
public class LauncherActivity extends ParentActivity {

    @ViewInject(R.id.activity_index_frame)
    private View frame;
    @ViewInject(R.id.activity_index_progress_label)
    private TextView label;
    @ViewInject(R.id.activity_index_progress)
    private Progressbar progressbar;

    @Override
    protected Object inflateView() {
        return R.layout.activity_launcher;
    }

    @Override
    protected void initView(View anchor) {

        if (Utils.isDebuggable(getApplicationContext()))
            Utils.wakeup(getApplicationContext());

        setSystemBarTransparent();

//        if (BuildConfig.ROLE == -1) {
//            jumpTo(HomePageActivity.class);
//            return;
//        }
        checkUpdate();
    }


    private void checkUpdate() {
        String weexVesion = WeexLoader.obtain(getApplicationContext()).getWeexVersionName();
        SDK.api().checkUpdate(weexVesion)
                .tag(this)
                .callback(new HttpCallback<UpdateInfo>() {
                    @Override
                    protected void onSuccess(UpdateInfo data) {
                        super.onSuccess(data);
                        if (data == null)
                            return;
                        try {
                            Version version = new Version();
                            switch (data.getCode()) {
                                case 1:
                                    version.setType("native");
                                    version.setUrl(SDK.api().downloadApk(Download.create()).url());
                                    version.setName(data.getApkInfo().getFileName());
                                    break;
                                case 2:
                                    version.setType("hybrid");
                                    version.setUrl(SDK.api().downloadWeex(Download.create()).url());
                                    version.setName(data.getWeexInfo().getFileName());
                                    break;
                                default:
                                    checkUpdate(null);
                                    return;
                            }
                            version.setStatus(1);
                            checkUpdate(version);
                            return;
                        } catch (Exception e) {
                            Logger.debug(e);
                        }
                        checkUpdate(null);
                    }

                    @Override
                    protected void onTimeout(Exception e) {
                        super.onTimeout(e);
                        checkUpdate(null);
                    }

                    @Override
                    protected void onFailure(Exception e) {
                        super.onFailure(e);
                        checkUpdate(null);
                    }

                    @Override
                    protected void onCancel() {
                        super.onCancel();
                        checkUpdate(null);
                    }
                });
    }

    public void checkUpdate(final Version bean) {
        if (bean != null && bean.getStatus() == 1) {
            if ("native".equals(bean.getType())) {
                if (!TextUtils.isEmpty(bean.getUrl())) {
                    String vName = TextUtils.isEmpty(bean.getVersionName()) ? bean.getName() : bean.getVersionName();
                    ApkVersion versionInfo = new ApkVersion(vName, bean.getVersionCode());
                    int curCode = ApkUtils.getVersionCode(this);
                    int newCode = versionInfo.getVersionCode();
                    Version curVersion = UpdateXml.obtain(this).getNewVersion();
                    int checkCode = curVersion != null ? curVersion.getVersionCode() : 0;
                    if (newCode > 0 && newCode > curCode && newCode > checkCode) {
                        if (TextUtils.isEmpty(bean.getVersionName()))
                            bean.setVersionName(versionInfo.getVersionName());
                        if (bean.getVersionCode() == 0)
                            bean.setVersionCode(newCode);
                        UpdateXml.obtain(this).setNewVersion(bean);
                    }
//                    UpdateUtil.downloadAPK(this, bean.getUrl(), bean.getName());
                }
            } else if ("hybrid".equals(bean.getType()) && !TextUtils.isEmpty(bean.getName())) {
                String versionName = bean.getName().substring(0, bean.getName().lastIndexOf("."));
                WeexVersion l = WeexLoader.obtain(this).getWeexVersion();
                WeexVersion r = new WeexVersion(null, versionName);
                if (r.compare(l) <= 0) {
                    Logger.debug("No need update :(%s>%s)", l.getVersion(), r.getVersion());
                    return;
                }
                if (r != null)
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            updateWeex(bean.getUrl(), bean.getName());
                        }
                    });
                return;
            }
        }
        finishCheck();
    }

    private void checkJumpMode() {
        String username = XmlData.getInstance().getUsername();
        String password = XmlData.getInstance().getPassword();
        if (TextUtils.isEmpty(username) || TextUtils.isEmpty(password) || !XmlConfig.getInstance().isAutoLogin()) {
            jumpTo(LoginActivity.class);
        } else {
            login(username, password);
//            Disposable disposable = SDK.api().login(username, password)
//                    .flowable()
//                    .subscribe(new Consumer<String>() {
//                        @Override
//                        public void accept(@NonNull String result) throws Exception {
//                            if (result != null && result.getStatus().equals("1") && result.getResult() != null) {
//                                XmlData.getInstance().setUserInfo(res);
//
//                                jumpTo(HomePageActivity.class);
//                            } else {
//                                jumpTo(LoginActivity.class);
//                            }
//                        }
//                    }, new Consumer<Throwable>() {
//                        @Override
//                        public void accept(@NonNull Throwable throwable) throws Exception {
//                            jumpTo(LoginActivity.class);
//                        }
//                    });
//            addSubscribe(disposable);
        }
    }

    private void login(final String username,final String password){
        if (TextUtils.isEmpty(username) && TextUtils.isEmpty(password)) {
            warn(getString(R.string.error_login_null_unpwd));
        } else if (TextUtils.isEmpty(username)) {
            warn(getString(R.string.error_login_null_un));
        } else if (TextUtils.isEmpty(password)) {
            warn(getString(R.string.error_login_null_pwd));
        } else if (!Utils.isNetworkAvailable(this)) {
            warn(getString(R.string.net_is_not_available));
            return;
        } else{
            ProgressDialog.show(this);
            SDK.api().login(username,password).postEvent(RequestCode.REQUEST_CODE_GET_LOGIN);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getLoginData(HttpEvent<String> httpEvent){
        int requestCode = httpEvent.getRequestCode();
        if (requestCode != RequestCode.REQUEST_CODE_GET_LOGIN) {
            ProgressDialog.dismiss();
            return;
        }

        if (httpEvent.getState() != HttpEvent.STATE_SUCCESS) {
            ProgressDialog.dismiss();
            return;
        } else {
            switch (requestCode){
                case RequestCode.REQUEST_CODE_GET_LOGIN:

                    Type type = new TypeToken<LandResult<LogInResult<UserInfo>>>(){}.getType();
                    LandResult<LogInResult<UserInfo>> result = GsonUtil.fromJson(httpEvent.getData(),type);
                    switch (result.getStatus()){
                        case "1":
                            XmlData.getInstance().setUserInfo(result.getResult().getUserInfo());
                            XmlConfig.getInstance().setAutoLogin(true);
                            jumpTo(HomePageActivity.class);
                            break;
                        case "2":
                            warn(result.getMessage());
                            break;
                    }

                    break;
                default:
                    break;
            }
        }
    }

    private boolean jumpTo(Class<? extends ParentActivity> clz) {
        if (Utils.startActivity(getApplicationContext(), clz, Intent.FLAG_ACTIVITY_CLEAR_TASK)) {
            return true;
        } else
            return false;
    }

    @Override
    public void onBackPressed() {
        moveTaskToBack(false);
    }

    private void finishCheck() {
        checkJumpMode();
    }


    private void updateWeex(final String url, final String weexName) {
        if (progressbar != null) {
            progressbar.setShowPercentText(true);
            progressbar.setProgressColor(Color.parseColor("#EE7942"));
            progressbar.setBackgroundColor(Color.parseColor("#55EAEAEA"));
            progressbar.setCornerRadius(DisplayUtil.dp2px(8));
            progressbar.setProgressDrawable(progressbar.generateDrawable());

            progressbar.setMax(100);
        }

        Download download = Download.create(url)
                .target(new File(getExternalCacheDir(), weexName))
                .overwrite(true)
                .progress(new HttpDownloadListener<String>() {
                    @Override
                    public void onProgress(String data, long progress, long length, float percent, float speed) {
                        if (progressbar != null)
                            progressbar.setProgress((int) (progressbar.getMax() * progress / length * 1.0));
                    }
                });

        SDK.api().downloadWeex(download).callback(new HttpCallback<File>() {
            @Override
            protected void onStart() {
                if (frame != null)
                    frame.setVisibility(View.VISIBLE);
                if (label != null)
                    label.setText(getString(R.string.version_update_download));
            }

            @Override
            protected void onTimeout(Exception e) {
                super.onTimeout(e);
                onFailure(null);
            }

            @Override
            protected void onFailure(Exception e) {
                super.onFailure(e);
                if (label != null)
                    label.setText(getString(R.string.version_update_error));
                finishCheck();
            }

            @Override
            protected void onSuccess(File data) {
                super.onSuccess(data);
                if (data != null && data.exists() && data.isFile()) {
                    unzip(data);
                } else
                    onFailure(null);
            }

            @Override
            protected void onFinish() {
                super.onFinish();
            }
        });
    }

    private void unzip(final File from) {
        try {
            if (label != null)
                label.setText(getString(R.string.version_update_install));
            if (progressbar != null)
                progressbar.setProgress(0);
            String target = WeexLoader.obtain(this).getWeexCacheFile();
            WeexUpdate weexZip = new WeexUpdate();
            weexZip.unzip(from, target, new OnUpdateListening() {
                @Override
                public void onProgress(int percentDone, String fileName) {
                    if (progressbar != null)
                        progressbar.setProgress((int) (1.0F * percentDone / 100 * progressbar.getMax()));
                }

                @Override
                public void onCancel() {
                }

                @Override
                public void onFailed(Exception e) {
                    Logger.debug(e);
                    if (label != null)
                        label.setText(getString(R.string.version_update_error));
                }

                @Override
                public void onSucceed(String versinName) {
                    if (progressbar != null)
                        progressbar.setProgress(progressbar.getMax());
                    WeexLoader weexLoader = WeexLoader.obtain(getApplicationContext());
                    weexLoader.setWeexFileVersion(versinName);
                    if (label != null)
                        label.setText(getString(R.string.version_update_done));
                }

                @Override
                public void onFinish() {
                    if (from != null && from.exists() && from.isFile()) {
                        from.delete();
                    }
                    finishCheck();
                }
            });
        } catch (Exception e) {
            Logger.debug(e);
            finishCheck();
        }
    }

    SweetAlertDialog mDialogWarn;

    public void warn(String message) {

        mDialogWarn = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                .setTitleText(message)
                .setContentText("")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismissWithAnimation();
                    }
                });
        mDialogWarn.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                mDialogWarn = null;
            }
        });
        mDialogWarn.show();
    }

}
